/***************************************************************************
 *   Copyright (C) 2007 by Ziman & Xloverin                                *
 *   ziman@centrum.sk, xloverin@gmail.com                                  *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

#include "log.h"
#include "terminal.h"

#include <QDateTime>
#include <QTextStream>

#define INIT_TIMESTAMP "%d.%m.%y, %H:%M:%S"

QString Log::filter(QString title)
{
	bool collapse = false;
	QString result = "";
	int len = title.size();

	for (int i = 0; i < len; ++i) {
		const QChar ch = title.at(i);

		if (ch.isLetterOrNumber()) {
			collapse = false;
			result.append(ch.toLower());
		} else {
			if (!collapse) {
				result.append('_');
				collapse = true;
			}
		}
	}
	return result;
}

QString Log::two(int x)
{
	if (x < 10) {
		return "0" + QString::number(x);
	} else {
		return QString::number(x);
	}
}

QString Log::format(QString format, QString title, QDateTime now)
{
	QString s;
	QString filteredTitle = filter(title);

	int len = format.size();
	for (int i = 0; i < len; ++i) {
		char ch = format.at(i).toAscii();
		if (ch == '%') {
			++i;
			if (i >= len) {
				s += '%';
				break;
			}
			ch = format.at(i).toAscii();
			switch (ch) {
				case 'y': s += QString::number(now.date().year()); break;
				case 'm': s += two(now.date().month()); break;
				case 'd': s += two(now.date().day()); break;
				case 'H': s += two(now.time().hour()); break;
				case 'M': s += two(now.time().minute()); break;
				case 'S': s += two(now.time().second()); break;
				case 'q': s += filteredTitle; break;
				default:
					s += ch;
			}
		} else {
			s += ch;
		}
	}

	return s;
}

void Log::setPrefs(const Log::Prefs &prefs)
{
	stop();
	this->prefs = prefs;
}

void Log::stop()
{
	QTextStream s;
	for (QMap<QString, QFile *>::const_iterator it = files.begin(); it != files.end(); ++it) {
		QFile *f = *it;
		s.setDevice(f);
		s << format(prefs.timestamp, "sys") << ' ' << tr("Log closed.") << "\n";
		s.flush();
		delete f;
	}
	files.clear();
}

QFile *Log::getFile(const QString &fn, PrefsLog::Format fileFormat, Terminal *terminal)
{
	QTextStream s;
	if (!files.contains(fn)) {

		QDir dir;
		QString dirName = fn;
		dirName.replace('\\', '/');
		dirName.truncate(dirName.lastIndexOf('/'));
		dir.mkpath(dirName);

		QFile *f = new QFile(fn);
		bool newFile = !f->exists();
		f->open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text);
		files.insert(fn, f);

		s.setDevice(f);

		switch (fileFormat) {
			case PrefsLog::Plaintext:
			case PrefsLog::Vt100:
				s << format(INIT_TIMESTAMP, "sys") << ' ' << tr("Log opened.") << "\n";
				break;

			case PrefsLog::Html:
				if (newFile) {
					s << "<html><head><title>Talker log: " << fn << "</title>" <<
						"<style>" << terminal->css() << "</style></head><body>";
				}
				s << "<h1>" << format(INIT_TIMESTAMP, "sys") << ' ' << tr("Log opened.") << "</h1>\n";
				break;

			case PrefsLog::PlainHtml:
				if (newFile) {
					s << "<html><head><title>Talker log: " << fn << "</title>"
						"<style>"
						" body { font-family: monospace; }"
						"</style> </head><body>";
				}
				s << "<h1>" << format(INIT_TIMESTAMP, "sys") << ' ' << tr("Log opened.") << "</h1>\n";
				break;
		}
		s.flush();
	}

	return files[fn];
}

void Log::write(QString title, PrefsLog::Format fileFormat, QString text, Terminal *terminal)
{
	QString ext;
	switch (fileFormat) {
		case PrefsLog::Html: ext = ".html"; break;
		case PrefsLog::PlainHtml: ext = "-plain.html"; break;
		case PrefsLog::Vt100: ext = ".vt100"; break;
		case PrefsLog::Plaintext: ext = ".txt"; break;
		default:
			ext = ".txt";
	}

	QString fileName = format(prefs.fileName, title) + ext;
	QFile *f = getFile(fileName, fileFormat, terminal);
	QTextStream s(f);
	if (prefs.timestampEnabled) {
		if (fileFormat & (PrefsLog::Html | PrefsLog::PlainHtml)) {
			s <<	"<span class=\"timestamp\">" <<
					format(prefs.timestamp, title) <<
					"</span> ";
		} else {
			s << format(prefs.timestamp, title) << ' ';
		}
	}
	s << text;
}

Log::Log()
{
}


Log::~Log()
{
	stop();
}


